package feng.demo.controller;

import cn.dev33.satoken.secure.SaBase64Util;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import feng.demo.dao.LargefileDao;
import feng.demo.dao.UserDao;
import feng.demo.entity.*;
import feng.demo.service.*;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    CartService cartService;
    @Autowired
    CommodityService commodityService;
    @Autowired
    LargefileDao largefileDao;
    @Autowired
    RemarkService remarkService;
    @Autowired
    RedisTemplate redisTemplate;
    @GetMapping("/info")
    public SaResult getUserInfo(){
        Object phone = StpUtil.getLoginId();
        User user = userService.findByPhone(String.valueOf(phone));
        user.setPassword("*************");
        return SaResult.data(user);
    }

    @GetMapping("/addCart/{id}")
    public String addCart(@PathVariable("id") Integer comid){
//        添加进购物车
        Object phone = StpUtil.getLoginId();
        User user = userService.findByPhone(String.valueOf(phone));
        Commodity com = commodityService.findById(comid);
        Cart cart = new Cart();
        cart.setCommodity(com);
        cart.setUser(user);
        cart.setNum(1);
        cart.setPrice(com.getPrice());
        int update = cartService.update(cart);
        if (update==0) {
            cartService.add(cart);
        }
        return new XJson(200,"添加成功",cart).toString();
    }


    @GetMapping("/findCart")
    public String findCart(){
//        查询我的购物车
        Object phone = StpUtil.getLoginId();
        User user = userService.findByPhone(String.valueOf(phone));
        List<Cart> carts = cartService.findByUid(user.getUid());
        return new XJson(200,"",carts).toString();
    }
    @PostMapping("/updateCart")
    public String updataCart(Cart cart,Integer comid){
//        更改购物车商品数量
        Commodity com = commodityService.findById(comid);
        if (com.getStock()<cart.getNum())return new XJson(401,"库存不足","").toString();
        cart.setCommodity(com);
        cart.setPrice(cart.getNum()*com.getPrice());
        cartService.update(cart);
        Object phone = StpUtil.getLoginId();
        User user = userService.findByPhone(String.valueOf(phone));
        List<Cart> carts = cartService.findByUid(user.getUid());
        return new XJson(200,"",carts).toString();
    }
    @GetMapping("/del/{id}")
    public String delCart(@PathVariable("id")Integer cartid){
//        删除购物车
        int del = cartService.del(cartid);
        Object phone = StpUtil.getLoginId();
        User user = userService.findByPhone(String.valueOf(phone));
        List<Cart> carts = cartService.findByUid(user.getUid());
        return new XJson(200,"删除成功",carts).toString();
    }
    @PostMapping("/updatapwd")
    public String updatapwd(String oldpwd,String newpwd){
            Object phone = StpUtil.getLoginId();
            User user = userService.findByPhone(String.valueOf(phone));
            String pwd = SaBase64Util.decode(user.getPassword());
            if (oldpwd.equals(pwd)){
                User u = new User();
                u.setUid(user.getUid());
                String p = SaBase64Util.encode(newpwd);
                u.setPassword(p);
                userService.update(u);
                return new XJson(200,"修改成功","").toString();
            }
            return new XJson(401,"旧密码不一致","").toString();

    }
    @PostMapping("/updatePic")
    public String updatePic(@RequestParam(value = "pic",required = false)MultipartFile pic){
//        修改头像
        if (pic!=null){
            Object phone = StpUtil.getLoginId();
            User user = userService.findByPhone(String.valueOf(phone));
            largefileDao.delete(user.getPic());
            Largefile largefile = new Largefile();
            try {
                largefile.setFilename(pic.getOriginalFilename());
                byte[] bytes=pic.getBytes();
                largefile.setContent(bytes);
            }catch (Exception e){

            }
            Integer integer = largefileDao.add(largefile);
            user.setPic(largefile.getId());
            userService.update(user);
            return new XJson(200,"修改成功",integer).toString();
        }


        return new XJson(401,"修改失败","").toString();
    }

    @GetMapping("/findByUidComid/{uid}/{comid}")
    public String findByUidComid(@PathVariable("uid")Integer uid,@PathVariable("comid")Integer comid){
        Map<String,Object> map=new HashMap<>();
        User user = userService.findByUid(uid);
        Commodity commodity = commodityService.findById(comid);
        map.put("user",user);
        map.put("com",commodity);
        return new XJson(200,"",map).toString();
    }

    @GetMapping("/findByComid/{comid}")
    public String findByComid(@PathVariable("comid")Integer comid){
        Map<String,Object> map=new HashMap<>();
        Commodity commodity = commodityService.findById(comid);
        User user = userService.findByUid(commodity.getUser().getUid());
        map.put("user",user);
        map.put("com",commodity);
        return new XJson(200,"",map).toString();
    }


    @PostMapping("/add")
    public String add(Remark remark){
        Object phone = StpUtil.getLoginId();
        User user = userService.findByPhone(String.valueOf(phone));
        remark.setUser(user);
        remarkService.add(remark);
        return new XJson(200,"评论成功","").toString();
    }


    @GetMapping("/quit")
    public String quit(){
//        退出
        Object phone = StpUtil.getLoginId();
        User user = userService.findByPhone(String.valueOf(phone));
        redisTemplate.delete(""+user.getPhone());
        StpUtil.logout(user.getPhone());
        return new XJson(200,"退出成功","").toString();
    }



    @PostMapping("/updateUser")
    public String updateUser(User user){
        Object phone = StpUtil.getLoginId();
        User u = userService.findByPhone(String.valueOf(phone));
        user.setUid(u.getUid());
        int update = userService.update(user);
        User user2 = userService.findByUid(u.getUid());
        user2.setPassword("*************");

        return  new XJson(200,"修改成功",user2).toString();
    }

}
